<template>
  <div class="layout-container sift-info-parmas" v-loading="loading">
    <FlowStep :activeStep="2" />
    <el-form
      class="baseinfo"
      :model="ruleForm"
      :inline="true"
      ref="formRef"
      label-width="85px"
    >
      <BaseInfoForm style="padding: 0" />

      <TagIcon title="选择被评估样本基础类型" />
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item
            label="作战场景"
            prop="preSampleBaseInfoParam.operatingScen"
            :rules="{
              required: true,
              message: '请选择',
              trigger: 'change',
            }"
          >
            <el-select
              v-model="ruleForm.preSampleBaseInfoParam.operatingScen"
              clearable
              placeholder="请选择"
            >
              <el-option label="对地" value="对地" />
              <el-option label="对海" value="对海" />
              <el-option label="对空" value="对空" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="干扰类型"
            prop="preSampleBaseInfoParam.interType"
            :rules="{
              required: true,
              message: '请选择',
              trigger: 'change',
            }"
          >
            <el-select
              v-model="ruleForm.preSampleBaseInfoParam.interType"
              clearable
              placeholder="请选择"
            >
              <el-option label="舰载有源干扰-雷达" value="舰载有源干扰-雷达" />
              <el-option label="舷外有源干扰-雷达" value="舷外有源干扰-雷达" />
              <el-option label="箔条干扰-雷达" value="箔条干扰-雷达" />
              <el-option label="角反干扰-雷达" value="角反干扰-雷达" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="导引头体制"
            prop="preSampleBaseInfoParam.dytStyle"
            :rules="{
              required: true,
              message: '请选择',
              trigger: 'change',
            }"
          >
            <el-select
              v-model="ruleForm.preSampleBaseInfoParam.dytStyle"
              clearable
              placeholder="请选择"
            >
              <el-option label="雷达(主动)" value="雷达(主动)" />
              <el-option label="雷达(被动)" value="雷达(被动)" />
              <el-option label="红外" value="红外" />
              <el-option label="雷达-红外符合制导" value="雷达-红外符合制导" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="外军电子战备类型"
            prop="preSampleBaseInfoParam.foreignElectEquip"
            label-width="120px"
            :rules="{
              required: true,
              message: '请选择',
              trigger: 'change',
            }"
          >
            <el-select
              v-model="ruleForm.preSampleBaseInfoParam.foreignElectEquip"
              clearable
              placeholder="请选择"
            >
              <el-option label="舰载有源干扰" value="舰载有源干扰" />
              <el-option label="舷外有源干扰" value="舷外有源干扰" />
              <el-option label="角反干扰" value="角反干扰" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="干扰场景类型"
            prop="preSampleBaseInfoParam.interScenType"
            label-width="120px"
            :rules="{
              required: true,
              message: '请选择',
              trigger: 'change',
            }"
          >
            <el-select
              v-model="ruleForm.preSampleBaseInfoParam.interScenType"
              clearable
              placeholder="请选择"
            >
              <el-option label="单一干扰" value="单一干扰" />
              <el-option label="组合干扰" value="组合干扰" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="key-params">
        <TagIcon title="选择关键影响参数" />
        <el-icon :size="16" color="rgba(24, 81, 237, 1)" @click="onAdd">
          <CirclePlus />
        </el-icon>
      </div>

      <div class="key-influence-params">
        <div v-for="(item, index) in keyInfluenceParamList" :key="index">
          <div class="params-item">
            <el-form-item
              :label="item.fieldName"
              :prop="item.fieldCode"
              label-width="120px"
            >
              <el-input
                v-model="ruleForm.keyParams[item.fieldCode]"
                placeholder="请输入"
              >
                <template #suffix>
                  <el-icon :size="15">
                    <Remove
                      @click="
                        () => {
                          onRemove(item, index);
                        }
                      "
                    />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
        </div>
      </div>

      <div class="step-buttons common-buttons">
        <el-button type="primary" @click="onBack">上一步</el-button>
        <el-button type="primary" @click="onStep(formRef)">下一步</el-button>
      </div>
    </el-form>
    <el-dialog
      v-model="dialogVisible"
      title="添加关键影响参数"
      width="400"
      destroy-on-close
      :before-close="handleClose"
    >
      <el-form class="baseinfo" ref="keyParamRef" :model="addkeyParamRuleForm">
        <el-form-item
          label="上级字段标识:"
          prop="pfieldName"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="addkeyParamRuleForm.pfieldName"
            clearable
            placeholder="请选择"
            @change="onKeyFields"
          >
            <el-option
              v-for="(item, index) in parentFieldList"
              :label="item.fieldName"
              :value="item.fieldCode + '-' + item.fieldName"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="关键影响参数:"
          prop="keyInfluName"
          :rules="{
            required: true,
            message: '请选择',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="addkeyParamRuleForm.keyInfluName"
            clearable
            placeholder="请选择"
            @visible-change="onOpen"
            @change="onKeyFieldLevel"
          >
            <el-option
              v-for="(item, index) in fieldLevelList"
              :label="item.fieldName"
              :value="item.fieldCode + '-' + item.fieldName"
              :key="index"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer common-buttons">
          <el-button type="primary" @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="onOk"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CirclePlus, Remove } from '@element-plus/icons-vue';
import {
  ElMessage,
  FormInstance,
  ElMessageBox,
  ElTable,
  ElSelect,
} from 'element-plus';
import TagIcon from '@/components/tag-icon/index.vue';
import BaseInfoForm from '../../BaseInfoForm/index.vue';
import {
  httpGetKeyPara,
  httpSingleStaticSimilaritySiftInfoParam,
  httpKeyField,
} from '@/api/similarityEvaluationSystem';
import { reverseContentType } from '@/utils/tools';
import FlowStep from '../../FlowStep/index.vue';
import { toggleRowStatus } from 'element-plus/es/components/table/src/util';
import { resolve } from 'dns';

let $router = useRouter();
const route = useRoute();

const formRef = ref<FormInstance>();
let ruleForm = ref<any>({
  preSampleBaseInfoParam: {
    operatingScen: '',
    dytStyle: '',
    interScenType: '',
    interType: '',
    foreignElectEquip: '',
  },
  keyParams: {},
});
const keyInfluenceParamList = ref<any>([]);
const dialogVisible = ref<boolean>(false);
const addkeyParamRuleForm = ref({
  pfieldName: '',
  pfieldCode: '',
  keyInfluName: '',
  formItemLabel: '', // 新增时标签名称
  formItemProp: '', // 标签的字段名
});
// 一级字段
const parentFieldList = ref<any>([]);
const fieldLevelList = ref([]);
const loading = ref<boolean>(false);

onMounted(() => {
  getKeyPara();
  getKeyField('2', '');
});

const getKeyField = (fieldLevel: string, pfieldCode: string = '') => {
  httpKeyField({ fieldLevel, pfieldCode }).then((res: any) => {
    const { code, data } = res;
    if (code === 200) {
      if (fieldLevel === '3') {
        fieldLevelList.value = data;
      } else {
        parentFieldList.value = data;
      }
    }
  });
};

// 分割字符串
const splitStr = (str: string): any => {
  const arr = str.split('-');
  if (arr && arr.length) {
    const code: string = arr[0];
    const name: string = arr[1];
    return { code, name };
  }
};

// 上级标识选择
const onKeyFields = (value: string) => {
  const { code, name } = splitStr(value);
  getKeyField('3', code);
  addkeyParamRuleForm.value = {
    ...addkeyParamRuleForm.value,
    pfieldCode: code,
    pfieldName: name,
  };
};

// 关键影响参数下拉框展示/隐藏
const onOpen = (visible: boolean) => {
  if (visible) {
    if (!addkeyParamRuleForm.value.pfieldName) {
      ElMessage({
        message: '请先选择上级字段标识',
        type: 'warning',
      });
      return;
    }
  }
};

// 关键影响参数选择事件
const onKeyFieldLevel = (value: string) => {
  const { code, name } = splitStr(value);
  addkeyParamRuleForm.value = {
    ...addkeyParamRuleForm.value,
    keyInfluName: name,
    formItemLabel: name,
    formItemProp: code,
  };
};

// 新增
const onAdd = () => {
  dialogVisible.value = true;
};

// 删除
const onRemove = (item: any, key: number) => {
  const index = keyInfluenceParamList.value.indexOf(item);
  if (index !== -1) {
    keyInfluenceParamList.value.splice(index, 1);
    const keyParamsObj = ruleForm.value.keyParams;
    let obj = {};
    for (let key in keyParamsObj) {
      if (key !== item.fieldCode) {
        obj[key] = keyParamsObj[key];
      }
    }
    ruleForm.value.keyParams = obj;
  }
};

// 确定
const onOk = () => {
  dialogVisible.value = false;
  keyInfluenceParamList.value.push({
    fieldName: addkeyParamRuleForm.value.formItemLabel,
    fieldCode: addkeyParamRuleForm.value.formItemProp,
    pfieldName: addkeyParamRuleForm.value.pfieldName,
    pfieldCode: addkeyParamRuleForm.value.pfieldCode,
  });
  ruleForm.value.keyParams = {
    ...ruleForm.value.keyParams,
    fieldCode: addkeyParamRuleForm.value.keyInfluName,
  };
};

// 得到关键影响参数
const getKeyPara = () => {
  loading.value = true
  httpGetKeyPara({ sampleId: route.query.dealSampleId }).then((res: any) => {
    const { code, data } = res;
    if (code === 200) {
      loading.value = false
      sessionStorage.setItem(
        'baseInfoVO',
        JSON.stringify(data.sampleBaseInfoVO)
      );
      keyInfluenceParamList.value = data.keyPara;
      filterFields(data.keyPara);
    }
  });
};

const filterFields = (arr: any) => {
  let obj = {};
  for (let i = 0; i < arr.length; i++) {
    const fieldCode = arr[i].fieldCode;
    obj[fieldCode] = '';
  }
  ruleForm.value.keyParams = obj;
};

// 取消
const handleClose = () => {
  dialogVisible.value = false;
};

// 校验关键影响因数表单
const validKeyParamFields = async (fields: any) => {
  for (let key in fields) {
    if (!fields[key]) {
      return true;
    }
  }
};

// 处理关键影响参数, 关键影响参数的数据值都是Number
const dealParaList = (data: any) => {
  return data.map((item: any) => {
    let obj: any = {};
    obj.fieldName = item.fieldName;
    obj.fieldValue = Number(ruleForm.value.keyParams[item.fieldCode]);
    obj.pfieldName = item.pfieldName;
    return obj;
  });
};

// 下一步
const onStep = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  const isValidKeyParam = await validKeyParamFields(ruleForm.value.keyParams);
  if (isValidKeyParam) {
    ElMessageBox.confirm('关键影响参数存在未填项，请填写！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).catch(() => {});
    return;
  }

  await formEl.validate((valid, fields) => {
    if (valid) {
      const params = {
        preSampleBaseInfoParam: ruleForm.value.preSampleBaseInfoParam,
        sampleId: route.query.dealSampleId,
        paraList: dealParaList(keyInfluenceParamList.value),
      };
      loading.value = true;
      httpSingleStaticSimilaritySiftInfoParam(params).then((res: any) => {
        loading.value = false;
        const { code, data } = res;
        if (code === 200) {
          $router.push({
            path: '/similarityEvaluateSystem/staticEvaluate',
            query: {
              dealSampleId: route.query.dealSampleId,
              sampleName: route.query.sampleName
            },
          });
          sessionStorage.setItem('staticTable', JSON.stringify(data));
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 上一步
const onBack = () => {
  $router.push({
    path: '/similarityEvaluateSystem/testSampleSelected',
    query: {},
  });
};
</script>

<style lang="scss" scoped>
@import '@/assets/style/buttons';
.sift-info-parmas {
  position: relative;
  .step-buttons {
    display: flex;
    justify-content: center;
    box-shadow: 0px 0px 10px rgba(218, 222, 224, 1);
    padding: 10px 0;
    position: absolute;
    bottom: 0;
    width: 100%;
    left: 0;
  }
  :deep() {
    .el-select--small {
      width: 230px;
    }
  }
  .key-params {
    display: flex;
    .el-icon {
      cursor: pointer;
      margin-left: 5px;
      position: relative;
      top: 10px;
    }
  }
  .key-influence-params {
    display: flex;
    flex-wrap: wrap;
    .el-icon {
      cursor: pointer;
      color: rgba(24, 81, 237, 1);
      position: relative;
      right: -4px;
    }
    .params-item {
      // display: flex;
    }
  }
  .baseinfo {
    padding: 16px;
  }
}
</style>
